package com.dexstudio.xmlparser;

import java.io.IOException;
import java.util.LinkedList;

import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.util.Log;

import com.dexstudio.currency.entity.Currency;
import com.dexstudio.exceptions.EmptyXMLException;

public class CurrencyParser extends XMLParser {

	private static final String EXCHANGE_RATE = "exchangerate";
	private static final String EXCHANGE_CCY = "ccy";
	private static final String EXCHANGE_BUY = "buy";
	private static final String EXCHANGE_SALE = "sale";
	
	public CurrencyParser(String xmlString) throws ParserConfigurationException, SAXException, IOException, EmptyXMLException {
		super(xmlString);
	}
	
	public LinkedList<Currency> parse() {
		LinkedList<Currency> currencyList = new LinkedList<Currency>();
		NodeList nodeList = this.getDoc().getElementsByTagName(EXCHANGE_RATE);
		for(int i=0; i<nodeList.getLength(); i++) {
			Node node = nodeList.item(i);
			if(node.getNodeType() == Node.ELEMENT_NODE) {
				try {
					Node ccy = node.getAttributes().getNamedItem(EXCHANGE_CCY);
					Node buy = node.getAttributes().getNamedItem(EXCHANGE_BUY);
					Node sale = node.getAttributes().getNamedItem(EXCHANGE_SALE);
					
					Currency currency = new Currency();
					currency.setCcy(ccy.getNodeValue().toString());
					currency.setBuy(Float.parseFloat(buy.getNodeValue().toString()));
					currency.setSale(Float.parseFloat(sale.getNodeValue().toString()));
					
					currencyList.add(currency);
				} catch (Exception e) {
					Log.e("XMLParse", "Error: " + e.getMessage());
					continue;
				}
			}
		}
		return currencyList;
	}
}
